﻿using AiBLSmartEdu.Module.Chemistry.API.Services;
using Microsoft.Extensions.Logging;
using FrameworkCore.Events;
using Microsoft.Extensions.DependencyInjection;
using AiBLSmartEdu.Module.SmartChemistry.API.DTOs;
using Domain;
using FrameworkCore.Hubs;
using Microsoft.AspNetCore.SignalR;
using FrameworkCore.Constants;

namespace AiBLSmartEdu.Module.Chemistry.API.HandleEvents;

public partial class EventChemistry :
    IConsumer<Event<AskEvents>>
{
    private readonly ILogger<EventChemistry> _logger;
    private readonly ChemistryAskHelpers _chemistryAskHelpers;
    private readonly IServiceProvider _serviceProvider;
    private readonly IHubContext<SignalRHub> _hubContext;

    public EventChemistry(
        ILogger<EventChemistry> logger,
        ChemistryAskHelpers chemistryAskHelpers,
        IServiceProvider serviceProvider,
        IHubContext<SignalRHub> hubContext)
    {
        _logger = logger;
        _chemistryAskHelpers = chemistryAskHelpers;
        _serviceProvider = serviceProvider;
        _hubContext = hubContext;
    }

    public virtual async Task HandleEventAsync(Event<AskEvents> eventMessage)
    {
        string question = eventMessage.Entity.Question;
        if (!string.IsNullOrWhiteSpace(question))
        {
            bool isException=false;
            try
            {
                string answer = await _chemistryAskHelpers.FetchAnswerAsync(question);
                if (answer != null)
                {
                    using (var scope = _serviceProvider.CreateScope())
                    {
                        var chemistryAskServices = scope.ServiceProvider.GetRequiredService<ChemistryAskServices>();
                        await chemistryAskServices.UpdateAnswerAsync(new ChemistryAskUpdateAnswerInputModel
                        {
                            Id = eventMessage.Entity.Id,
                            Answer = answer,
                            Type = MessageType.Text
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                isException = true;
                _logger.LogError($"【{eventMessage.Entity.Id}：[{typeof(Event<AskEvents>)}]{ex.Message}】");
            }
            finally
            {
                string message = isException == true ? GlobalConstants.ChemistryAskFail : GlobalConstants.ChemistryAskCompleted;
                await _hubContext.Clients.Users(eventMessage.Entity.UserId).SendAsync(GlobalConstants.ReceivePrivateNotification, message);
            }
        }
    }
}